﻿using Microsoft.Xaml.Behaviors;
using System.Windows.Controls;
using System.Windows;
using CommunityToolkit.Mvvm.DependencyInjection;
using System;

namespace MachineVision.Core.Util.Navigation
{
    /// <summary>
    /// 区域导航功能-注册区域行为：将附加该行为的ContenControl控件添加到RegionManager容器中
    /// </summary>
    public class RegionRegisterBehavior : Behavior<ContentControl>
    {
        /// <summary>
        /// 设置区域名字
        /// </summary>
        public string RegionName
        {
            get { return (string)GetValue(RegionNameProperty); }
            set { SetValue(RegionNameProperty, value); }
        }
        public static readonly DependencyProperty RegionNameProperty =
            DependencyProperty.Register("RegionName", typeof(string), typeof(RegionRegisterBehavior));



        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += AssociatedObject_Loaded;
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            if (AssociatedObject.GetType().Name != "ContentControl")
            {
                return;
            }
            var a = (sender as ContentControl);
            if (string.IsNullOrEmpty(RegionName)) { throw new Exception($"区域注册时未设置RegionName"); }
            Ioc.Default.GetService<RegionManager>()?.RegionMaps.TryAdd(RegionName, a);
        }
    }
}